/**
 * 村民管理器
 * 负责村民的招募、管理和技能提升
 */

import { GAME_CONFIG, VILLAGER_NAMES } from '../config/game-config.js';

export class VillagerManager {
    constructor(gameData, resourceManager) {
        this.gameData = gameData;
        this.resourceManager = resourceManager;
    }

    /**
     * 招募村民
     * @returns {Object} {success: boolean, message: string, villager: Object}
     */
    recruitVillager() {
        // 检查人口上限
        if (this.gameData.resources.population >= this.gameData.resources.maxPopulation) {
            return {
                success: false,
                message: '人口已达上限，请升级民房增加人口容量'
            };
        }

        // 计算招募成本（随人口增加而增加）
        const cost = this.calculateRecruitCost();

        // 检查资源
        if (!this.resourceManager.hasEnoughResources(cost)) {
            return {
                success: false,
                message: `资源不足，需要${cost.wood}木材和${cost.food}粮食`
            };
        }

        // 扣除资源
        this.resourceManager.deductResources(cost);

        // 生成新村民
        const newVillager = this.generateVillager();
        this.gameData.villagers.push(newVillager);

        // 增加人口
        this.gameData.resources.population += 1;

        return {
            success: true,
            message: `成功招募村民: ${newVillager.name}`,
            villager: newVillager
        };
    }

    /**
     * 计算招募成本
     * @returns {Object} {wood: number, food: number}
     */
    calculateRecruitCost() {
        const baseWoodCost = GAME_CONFIG.RECRUIT.BASE_WOOD_COST;
        const baseFoodCost = GAME_CONFIG.RECRUIT.BASE_FOOD_COST;
        const multiplier = GAME_CONFIG.RECRUIT.COST_MULTIPLIER;
        const currentPopulation = this.gameData.resources.population;

        return {
            wood: Math.floor(baseWoodCost * Math.pow(multiplier, currentPopulation - 5)),
            food: Math.floor(baseFoodCost * Math.pow(multiplier, currentPopulation - 5))
        };
    }

    /**
     * 生成新村民
     * @returns {Object} 村民对象
     */
    generateVillager() {
        const newId = this.getNextVillagerId();
        const name = this.generateVillagerName();

        return {
            id: newId,
            name: name,
            skills: {
                farming: Math.random() * 0.5 + 1, // 1.0 - 1.5
                woodcutting: Math.random() * 0.5 + 1 // 1.0 - 1.5
            }
        };
    }

    /**
     * 获取下一个村民ID
     * @returns {number} 村民ID
     */
    getNextVillagerId() {
        if (this.gameData.villagers.length === 0) {
            return 1;
        }
        return Math.max(...this.gameData.villagers.map(v => v.id)) + 1;
    }

    /**
     * 生成村民名字
     * @returns {string} 村民名字
     */
    generateVillagerName() {
        const usedNames = this.gameData.villagers.map(v => v.name);
        const availableNames = VILLAGER_NAMES.filter(name => !usedNames.includes(name));

        if (availableNames.length > 0) {
            return availableNames[Math.floor(Math.random() * availableNames.length)];
        }

        // 如果所有名字都用完了，生成编号名字
        const baseName = VILLAGER_NAMES[Math.floor(Math.random() * VILLAGER_NAMES.length)];
        return `${baseName}${Math.floor(Math.random() * 100)}`;
    }

    /**
     * 获取村民
     * @param {number} villagerId - 村民ID
     * @returns {Object|null} 村民对象
     */
    getVillager(villagerId) {
        return this.gameData.villagers.find(v => v.id === villagerId) || null;
    }

    /**
     * 获取所有村民
     * @returns {Array} 村民列表
     */
    getAllVillagers() {
        return this.gameData.villagers;
    }

    /**
     * 提升村民技能
     * @param {number} villagerId - 村民ID
     * @param {string} skillType - 技能类型
     * @param {number} amount - 提升量
     * @returns {boolean} 是否成功
     */
    improveVillagerSkill(villagerId, skillType, amount) {
        const villager = this.getVillager(villagerId);

        if (!villager || !villager.skills.hasOwnProperty(skillType)) {
            return false;
        }

        villager.skills[skillType] += amount;
        return true;
    }

    /**
     * 更新所有村民技能（随机提升）
     */
    updateAllVillagersSkills() {
        this.gameData.villagers.forEach(villager => {
            // 随机选择一个技能提升
            const skills = Object.keys(villager.skills);
            const skillToUpgrade = skills[Math.floor(Math.random() * skills.length)];
            villager.skills[skillToUpgrade] += 0.1;
        });

        console.log('所有村民技能已更新');
    }

    /**
     * 计算平均技能水平
     * @param {string} skillType - 技能类型
     * @returns {number} 平均技能水平
     */
    getAverageSkillLevel(skillType) {
        if (this.gameData.villagers.length === 0) {
            return 1.0;
        }

        const total = this.gameData.villagers.reduce((sum, v) => {
            return sum + (v.skills[skillType] || 1);
        }, 0);

        return total / this.gameData.villagers.length;
    }

    /**
     * 获取招募信息（用于UI显示）
     * @returns {Object} 招募信息
     */
    getRecruitInfo() {
        const cost = this.calculateRecruitCost();
        const canRecruit = this.gameData.resources.population < this.gameData.resources.maxPopulation &&
                          this.resourceManager.hasEnoughResources(cost);

        return {
            cost: cost,
            canRecruit: canRecruit,
            currentPopulation: this.gameData.resources.population,
            maxPopulation: this.gameData.resources.maxPopulation,
            reachedLimit: this.gameData.resources.population >= this.gameData.resources.maxPopulation
        };
    }
}
